﻿using System.Collections.Generic;

namespace OpenLS.Spreadsheet.StandardAddIn.Statistics
{
    internal enum RegressionType

    {
        WithIntercept,
        WithoutIntercept
    }

    internal class Regression
    {
        private Matrix _t;
        private Matrix _x;
        private Matrix _y;

        public Regression(Matrix y, Matrix x)
        {
            Initialize(y, x);
        }

        public Regression(IEnumerable<double> y, IEnumerable<List<double>> x, RegressionType type)
        {
            var l = new List<double>(y);
            var yData = new double[l.Count][];
            for (int i = 0; i < yData.Length; i++)
            {
                yData[i] = new[] {l[i]};
            }
            var l2 = new List<List<double>>(x);
            var xData = new double[l2.Count][];
            for (int i = 0; i < xData.Length; i++)
            {
                var l3 = new List<double>(l2[i]);
                if (type == RegressionType.WithIntercept)
                    l3.Add(1d);
                xData[i] = l3.ToArray();
            }
            Initialize(new Matrix(yData), new Matrix(xData));
        }

        public IEnumerable<double> Coefficients
        {
            get
            {
                for (int i = 0; i < _t.RowCount; i++)
                    yield return _t[i, 0];
            }
        }

        private void Initialize(Matrix y, Matrix x)
        {
            this._y = y;
            this._x = x;
            Matrix xt = x.Transpose();
            _t = (xt*x).Inverse*xt*y;
        }
    }
}